package com.gxuwz.stats.service.excelhandler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.service.impl.DecisionConsultingServiceImpl;

import java.util.ArrayList;
import java.util.List;

public class DecisionConsultListener extends AnalysisEventListener<DecisionConsulting> implements ImportResultProvider{
    private boolean stopProcessing = false;
    private final List<DecisionConsulting> dataList = new ArrayList<>();
    private int ignoredCount = 0; // 新增：被忽略条数
    private final DecisionConsultingServiceImpl workloadService;

    private final String currentUsername;
    private final String currentRole;
    private final String currentDepartment;

    public DecisionConsultListener(DecisionConsultingServiceImpl workloadService, String username, String role, String department) {
        this.workloadService = workloadService;
        this.currentUsername = username;
        this.currentRole = role;
        this.currentDepartment = department;
    }

    @Override
    public void invoke(DecisionConsulting dto, AnalysisContext context) {
        if (stopProcessing) {
            return;
        }
        // 检查姓名是否为“说明”
        if (dto.getUsername().contains("说明")) {
            stopProcessing = true;
            return;
        }
        if ("普通用户".equals(currentRole)) {
            // 普通用户只能导入自己的数据
            if (!dto.getUsername().equals(currentUsername)) {
                ignoredCount++; // 统计被忽略
                return;
//                throw new RuntimeException("只能导入自己的数据，发现有不是本人的数据！");
            }
        } else if ("二级学院管理员".equals(currentRole)) {
            // 二级管理员只能导入本部门数据
            if (dto.getDepartment() == null || !dto.getDepartment().equals(currentDepartment)) {
                ignoredCount++;
                return;
//                throw new RuntimeException("只能导入本部门的数据，发现有不是本部门的数据！");
            }
        }
        // 处理有效数据
        dataList.add(dto);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 解析完成后批量保存
        workloadService.saveAllFromDTO(dataList);
    }
    @Override
    public int getImportedCount() {
        return dataList.size(); // 或你实际统计的变量
    }

    @Override
    public int getIgnoredCount() {
        return ignoredCount; // 或你实际统计的变量
    }
}
